﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Ionic.Zip;
using Kooboo.CMS.Content.Models;
using Kooboo.CMS.Content.Persistence;
using Kooboo.CMS.Content.Persistence.Default;
using Kooboo.CMS.DataModule.Models;

namespace Kooboo.CMS.DataModule.Services
{
    public class ImportService
    {
        public static string tempDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cms_Data", "Temp");
        public void ImportData(ImportModel model, Stream data)
        {
            var dataDir = Unzip(data);

            foreach(var file in Directory.EnumerateFiles(dataDir))
            {
                ImportDataByFile(file, model);
            }

            Directory.Delete(dataDir, true);
        }

        private void ImportDataByFile(string file, ImportModel importModel)
        {
            var contents = Serialization.Deserialize<List<TextContent>>(file);
            var textFolder = new TextFolder(Repository.Current, importModel.FolderName);
            var schema = textFolder.GetSchema();
            foreach(var item in contents)
            {
                item.FolderName = importModel.FolderName;
                item.SchemaName = schema.Name;

                /*if(!String.IsNullOrEmpty(item.ParentFolder) &&
                    !item.ParentFolder.Equals(item.FolderName, StringComparison.OrdinalIgnoreCase))
                {
                    item.ParentFolder = importModel.ParentFolder;
                    item.ParentUUID = importModel.ParentUUID;
                }*/

                item.Published = importModel.Published;
            }
            Providers.DefaultProviderFactory.GetProvider<ITextContentProvider>().ImportSchemaData(schema, contents);

            if(!string.IsNullOrEmpty(importModel.CategoryFolder))
            {
                var categoryData = contents.Select(it => new Category()
                {
                    ContentUUID = it.UUID,
                    CategoryFolder = importModel.CategoryFolder,
                    CategoryUUID = importModel.CategoryUUID
                });
                Providers.DefaultProviderFactory.GetProvider<ITextContentProvider>().ImportCategoryData(Repository.Current, categoryData);
            }
        }

        private string Unzip(Stream data)
        {
            var dataDir = Path.Combine(tempDir, Guid.NewGuid().ToString());
            using(ZipFile zipFile = ZipFile.Read(data, System.Text.Encoding.UTF8))
            {
                zipFile.ExtractAll(dataDir);
            }
            return dataDir;
        }
    }
}